package com.nowcoder.community.controller;

import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController {
    @Autowired
    private DiscussPostService discussService;
    @Autowired
    private UserService userService;

    //访问首页
    @RequestMapping(path = "/index",method = RequestMethod.GET)
    public String getIndex(Model model, Page page){
        //这俩属性没有默认值，需要自己设定
        page.setRows(discussService.findRowsCount(0));
        page.setPath("/index");//用于前端的链接，格式为/index?current=1

        List<DiscussPost> list = discussService.findDiscussPost(0,page.getStartRow(),page.getLimit());
        List<Map<String,Object>> discussPosts = new ArrayList<>();
        if(!list.isEmpty()){
            for(DiscussPost post:list){
                Map<String, Object> map = new HashMap<>();
                //帖子
                map.put("post",post);
                User user = userService.findUserById(post.getUserId());
                map.put("user", user);
                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts",discussPosts);
        return "/index";
    }

    //获取错误页面
    @RequestMapping(path = "/error",method = RequestMethod.GET)
    public String getErrorPage(){
        return "error/500";
    }


}
